from django_redis import get_redis_connection
from rest_framework import serializers
from rest_framework.serializers import ModelSerializer
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
import re

from user.models import UserModel


class CustomTokenSerializers(TokenObtainPairSerializer):
    @classmethod
    def get_token(cls, user):
        token = super().get_token(user)
        token['username'] = str(user.username)
        token['phone'] = str(user.phone)
        token['gender'] = str(user.gender)
        token['age'] = str(user.age)
        return token
# 验证码序列化器
class SmsLoginSerializers(ModelSerializer):
    access_token = serializers.CharField(max_length=500, read_only=True)
    refresh = serializers.CharField(max_length=500, read_only=True)
    code = serializers.CharField(max_length=6, write_only=True)
    class Meta:
        model = UserModel
        fields = ['phone', 'access_token','refresh', 'code']
    def validate(self, attrs):
        print("------------- validate -----------")
        print(attrs)
        phone = attrs.get('phone')  # 手机号
        code = attrs.get('code')    # 验证码
        redis = get_redis_connection("sms_code")  # 连接redis
        sms_code = redis.get(f"sms_{phone}")  # 获取redis中的验证码
        if not re.match(r"^1[3-9]\d{9}$",phone):    # 判断手机号格式
            raise serializers.ValidationError({"msg": "手机号格式错误","code":201})
        if not sms_code:    # 判断验证码是否存在
            raise serializers.ValidationError({"msg": "验证码过期","code":202})
        if sms_code.decode()!= code:    # 判断验证码是否正确
            raise serializers.ValidationError({"msg": "验证码错误","code":203})
        attrs.pop('code')    # 验证码不返回给前端
        return attrs
    # 判断手机号是否存在
    def create(self, validated_data):
        phone = validated_data.get('phone')
        user = UserModel.objects.filter(phone=phone).first()    # 判断手机号是否存在 .first()返回第一个匹配的对象
        if user:
            print("手机号已存在，登录成功")
            data_refresh = CustomTokenSerializers.get_token(user)    # 获取token
            user.refresh =data_refresh
            user.access_token = data_refresh.access_token
            user.save()    # 保存token
            print("token创建成功",user.refresh.access_token)
            return user
        else:
            print("手机号不存在，创建新用户")
            password = UserModel.objects.make_random_password(length=10)    # 生成随机密码
            user = UserModel.objects.create_user(
                phone=phone,
                username=phone,
                password=password,
            )    # 创建用户
            print("用户创建成功")
            print("密码为：" + password)
            user.save()    # 保存用户信息
            data_refresh = CustomTokenSerializers.get_token(user)    # 获取token
            user.refresh =data_refresh
            user.access_token = data_refresh.access_token
            user.save()    # 保存token
            print("token创建成功",user)
            return user



